using System;
using System.IO;
using System.Windows.Forms;
using System.Threading;
using System.Drawing;
using System.Text.Json;

namespace TimeFileDeleter
{
    public partial class MainForm : Form
    {
        private string configPath = "config.txt";
        private NotifyIcon trayIcon;
        private ContextMenuStrip trayMenu;
        private System.Windows.Forms.Timer deleteTimer;  // 明确指定使用Windows.Forms.Timer
        
        public MainForm()
        {
            InitializeComponent();
            
            // 禁止窗体最大化
            this.MaximizeBox = false;
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            
            // 设置窗体最小化时不显示在任务栏
            this.ShowInTaskbar = true; // 默认显示
            this.Resize += (s, e) => 
            {
                if (this.WindowState == FormWindowState.Minimized)
                {
                    this.ShowInTaskbar = false;
                }
                else
                {
                    this.ShowInTaskbar = true;
                }
            };
            
            // 初始化系统托盘图标
            trayMenu = new ContextMenuStrip();
            trayMenu.Items.Add("显示", null, OnShow);
            trayMenu.Items.Add("退出", null, OnExit);
            
            trayIcon = new NotifyIcon();
            trayIcon.Text = "文件定时删除工具";
            trayIcon.Icon = SystemIcons.Application;
            trayIcon.ContextMenuStrip = trayMenu;
            trayIcon.Visible = true;
            trayIcon.DoubleClick += OnShow;
            
            // 初始化时间单位下拉框
            cmbTimeUnit.Items.AddRange(new object[] {"秒", "分钟", "小时", "天", "月", "年"});
            cmbTimeUnit.SelectedIndex = 0;
            
            // 初始化定时器
            deleteTimer = new System.Windows.Forms.Timer();
            deleteTimer.Tick += (s, e) => DeleteTimer_Tick(s, e);
            LoadConfig();
        }

        private void LoadConfig()
        {
            if (File.Exists(configPath))
            {
                try
                {
                    var json = File.ReadAllText(configPath);
                    var config = JsonSerializer.Deserialize<ConfigData>(json);
                    
                    txtPath.Text = config.Path?.Trim();
                    numInterval.Value = config.Interval;
                    if (cmbTimeUnit.Items.Count > 0 && config.TimeUnitIndex >= 0 && config.TimeUnitIndex < cmbTimeUnit.Items.Count)
                    {
                        cmbTimeUnit.SelectedIndex = config.TimeUnitIndex;
                    }
                }
                catch
                {
                    // 如果配置文件损坏，使用默认值
                    txtPath.Text = "";
                    numInterval.Value = 1;
                    cmbTimeUnit.SelectedIndex = 0;
                }
            }
        }

        private void SaveConfig()
        {
            var config = new ConfigData
            {
                Path = txtPath.Text?.Trim(),
                Interval = (int)numInterval.Value,
                TimeUnitIndex = cmbTimeUnit.SelectedIndex
            };
            
            var json = JsonSerializer.Serialize(config);
            File.WriteAllText(configPath, json);
        }

        private class ConfigData
        {
            public string? Path { get; set; } = null;
            public int Interval { get; set; }
            public int TimeUnitIndex { get; set; }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            // 创建上下文菜单
            var menu = new ContextMenuStrip();
            
            // 添加文件选择项
            menu.Items.Add("选择文件", null, (s, args) => 
            {
                using (var dialog = new OpenFileDialog())
                {
                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        txtPath.Text = dialog.FileName;
                    }
                }
            });
            
            // 添加文件夹选择项
            menu.Items.Add("选择文件夹", null, (s, args) => 
            {
                using (var dialog = new FolderBrowserDialog())
                {
                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        txtPath.Text = dialog.SelectedPath;
                    }
                }
            });
            
            // 显示菜单在按钮位置
            var btn = (Button)sender;
            menu.Show(btn, new Point(0, btn.Height));
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            // 防御性编程：确保控件存在且内容有效
            if (txtPath == null)
            {
                MessageBox.Show("程序内部错误：路径输入框未初始化");
                return;
            }
            
            string path = txtPath.Text?.Trim() ?? string.Empty;
            if (string.IsNullOrWhiteSpace(path))
            {
                MessageBox.Show("请先选择要删除的路径");
                return;
            }

            SaveConfig();
            
            bool success = false;
            try
            {
                if (string.IsNullOrEmpty(path))
                {
                    lblStatus.Text = "请先选择要删除的路径";
                    return;
                }

                if (Directory.Exists(txtPath.Text))
                {
                    // 删除目录下所有文件但不删除目录本身
                    foreach (string file in Directory.GetFiles(txtPath.Text))
                    {
                        File.Delete(file);
                    }
                    lblStatus.Text = $"已删除目录下所有文件: {txtPath.Text}";
                    success = true;
                }
                else if (File.Exists(txtPath.Text))
                {
                    File.Delete(txtPath.Text);
                    lblStatus.Text = $"已删除文件: {txtPath.Text}";
                    success = true;
                }
                else
                {
                    lblStatus.Text = "路径不存在";
                }
            }
            catch (Exception ex)
            {
                lblStatus.Text = $"删除失败: {ex.Message}";
            }

            // 只有删除成功时才最小化
            if (success && !string.IsNullOrEmpty(txtPath.Text))
            {
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
            }
            else if (string.IsNullOrEmpty(txtPath.Text))
            {
                MessageBox.Show("请先选择要删除的路径", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSchedule_Click(object sender, EventArgs e)
        {
            // 定时删除功能实现
            int interval = (int)numInterval.Value;
            int milliseconds = interval * 1000; // 默认秒
            
            if (cmbTimeUnit?.SelectedItem == null)
            {
                MessageBox.Show("请选择时间单位");
                return;
            }
            string timeUnit = cmbTimeUnit.SelectedItem.ToString()!;
            switch(timeUnit)
            {
                case "分钟":
                    milliseconds = interval * 60 * 1000;
                    break;
                case "小时":
                    milliseconds = interval * 60 * 60 * 1000;
                    break;
                case "天":
                    milliseconds = interval * 24 * 60 * 60 * 1000;
                    break;
                case "月":
                    milliseconds = interval * 30 * 24 * 60 * 60 * 1000;
                    break;
                case "年":
                    milliseconds = interval * 365 * 24 * 60 * 60 * 1000;
                    break;
            }
            
            // 保存当前设置
            SaveConfig();
            
            deleteTimer.Interval = milliseconds;
            deleteTimer.Start();
            // 立即执行一次删除
            if (MessageBox.Show($"确定要定时删除 {txtPath.Text} 吗？间隔: {interval}{cmbTimeUnit.SelectedItem}", 
                "确认", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                btnDelete.PerformClick();
              if(  !string.IsNullOrEmpty(txtPath.Text))
            {
                // 最小化到托盘
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
                
                lblStatus.Text = $"已设置定时删除 {txtPath.Text}，间隔: {interval}{cmbTimeUnit.SelectedItem}";
                }
            }
            else
            {
                lblStatus.Text = "已取消定时删除设置";
            }
        }
        private void OnShow(object? sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;
            this.Activate();
        }

        private void OnExit(object? sender, EventArgs e)
        {
            trayIcon.Visible = false;
            Application.Exit();
        }

        private void DeleteTimer_Tick(object? sender, EventArgs e)
        {
            try 
            {
                btnDelete.PerformClick();
                string logDir = "logs";
                string logFile = $"logs/delete_log_{DateTime.Now:yyyyMMdd}.txt";
                if (!Directory.Exists(logDir))
                {
                    Directory.CreateDirectory(logDir);
                }
                File.AppendAllText(logFile,
                    $"{DateTime.Now}: 成功删除 {txtPath.Text}\n");
            }
            catch (Exception ex)
            {
                string logDir = "logs";
                string logFile = $"logs/delete_log_{DateTime.Now:yyyyMMdd}.txt";
                if (!Directory.Exists(logDir))
                {
                    Directory.CreateDirectory(logDir);
                }
                File.AppendAllText(logFile,
                    $"{DateTime.Now}: 删除失败 {txtPath.Text} - {ex.Message}\n");
            }
        }
    }
}